const express = require('express');
const cors = require('cors');

const db = require('./config/database');

// const swaggerUi = require('swagger-ui-express');
// const swaggerSpec = require('./config/swagger');
// const todoRoutes = require('./routes/todoRoutes');

const path = require('path'); // 引入 path 模块，用于处理文件路径
const OSS = require('ali-oss');
require('dotenv').config();

const app = express();
app.use(express.json());
// 应该放在 API 路由定义之前。
app.use(express.static(path.join(__dirname, 'public')));
// # 使用中间件
app.use(cors({
    origin: ['http://localhost', 'http://192.168.147.21:3000'],
    methods: ['GET','PUT', 'POST'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    preflightContinue: false
  }));



// Swagger文档路由 (作为View层)
// app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

// API路由
// app.use('/todos', todoRoutes);

// 根路由重定向到API文档
// app.get('/', (req, res) => {
//   res.redirect('/api-docs');
// });

// 创建reviews表（如果还没有创建）

const pool = db.createPool(); 
const createTableQuery = `
CREATE TABLE IF NOT EXISTS reviews (
    id SERIAL PRIMARY KEY,
    user_id INT NOT NULL,
    user_name VARCHAR(255),
    restaurant_name VARCHAR(255) NOT NULL,
    restaurant_location VARCHAR(255) NOT NULL,
    dish_name VARCHAR(255),
    rating INT NOT NULL CHECK (rating >= 1 AND rating <= 5),
    review_text TEXT,
    image_path VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
`;

pool.query(createTableQuery)
  .then(() => console.log('表已创建或已存在'))
  .catch((err) => console.error('创建表失败:', err));


// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    error: '服务器内部错误',
    message: err.message
  });
});



// OSS客户端配置
const client = new OSS({
  region: process.env.OSS_REGION,
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  bucket: process.env.OSS_BUCKET,
});

// 生成上传用的预签名URL
app.get('/api/upload-url', async (req, res) => {
  try {
    const { filename, contentType } = req.query;
    if (!filename || !contentType) {
      return res.status(400).json({ error: '文件名和内容类型是必需的' });
    }

    const key = `uploads/${Date.now()}-${filename}`;
    const url = client.signatureUrl(key, {
      method: 'PUT',
      expires: 3600,
      'Content-Type': contentType
    });

    res.json({ 
      uploadUrl: url,
      fileKey: key,
      expiresIn: 3600
    });
  } catch (error) {
    console.error('生成预签名 URL 失败:', error);
    // 确保返回 JSON 格式
    res.status(500).json({ error: '生成预签名 URL 失败' });
  }
});

// 存储上传到OSS的文件位置
app.post('/api/upload-complete', async (req, res) => {
  const { fileKey } = req.body;

  // 使用 OSS 客户端获取文件 URL
  const fileUrl = await client.signatureUrl(fileKey, { method: 'GET' });

  res.json({ imagePath: fileUrl });
});




app.post('/api/reviews', async (req, res) => {
  const { userId, userName, restaurantName, restaurantLocation, dishName, rating, reviewText, imagePath } = req.body;

  if (!userId || !restaurantName || !restaurantLocation || !rating || !reviewText || !(typeof rating === 'number' && rating >= 1 && rating <= 5)) {
      return res.status(400).json({ error: '请求参数错误' });
  }

  try {
    const query = `
    INSERT INTO reviews (user_id, user_name, restaurant_name, restaurant_location, dish_name, rating, review_text, image_path)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?);
    `;

    const values = [userId, userName || null, restaurantName, restaurantLocation, dishName || null, rating, reviewText, imagePath || null];

    const result = await pool.query(query, values);
    const newReview = result.insertId;
    res.status(200).json({ id: newReview });
  } catch (error) {
    console.error('新增评价失败:', error);
    res.status(500).json({ error: '新增评价失败' });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
module.exports = app;